package com.itheima.reggie.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.record.DVALRecord;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart){//这里的shopping到底是什么
        log.info("购物车数据（新增）:{}",shoppingCart);
        //获取当前登录用户（根据id）,并赋值给购物车
        Long userid = UserHolder.get();
        //这样就知道当前是谁的购物车
        shoppingCart.setUserId(userid);
        //拿到想要添加的菜品id/套餐id
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        //添加前，要判断两件事：
        //① 判断当前添加是菜品还是套餐
        if( dishId != null){
            //是菜品,并判断是哪一道菜！
            qw.eq(ShoppingCart::getDishId,dishId);
        }else{
            //是套餐，并判断是哪一个套餐
            qw.eq(ShoppingCart::getSetmealId , setmealId);
        }
        //② 判断当前购物车内是否有目前即将要添加的菜品或套餐
        //SQL:select * from shopping_cart where user_id = ?
        //                      and dish_id/setmeal_id = ?
        ShoppingCart one = shoppingCartService.getOne(qw);
        if(one !=null){
            //已存在，在原来基础上数量加一
            one.setNumber(one.getNumber()+1);
            shoppingCartService.updateById(one);
        }else{
            //不存在，设置数量为1
            shoppingCart.setNumber(1);
            shoppingCart.setUserId(userid);//？？？
            shoppingCartService.save(shoppingCart);
        }

        return R.success(null);
    }

    /**
     * 查询购物车
     * @param session
     * @return
     */
    @GetMapping("/list")
    public R list(HttpSession session){
        log.info("查询购物车");
        //只能查看当前登录用户的购物车，可以从session中获取登录信息（userid）
        //或者Userholder
        Long userid = UserHolder.get();
        //Long userId = (Long) session.getAttribute("user");
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,userid);
        // select * from shoping_cart where user_id = ?
        List<ShoppingCart> list = shoppingCartService.list(qw);
        return R.success(list);
    }

    /**
     * 取消购物车（菜品/套餐）
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R sub(@RequestBody ShoppingCart shoppingCart){
        log.info("购物车数据（取消）:{}",shoppingCart);
        //获取当前登录的用户id
        Long userid = UserHolder.get();
        //这样就知道当前是谁的购物车
        shoppingCart.setUserId(userid);
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        //取消前要判断两件事：根据userid和dishId/setmealId去判断
        //① 判断当前要取消的是菜品还是套餐
        if( dishId != null){
            //是菜品,并判断是哪一道菜！
            qw.eq(ShoppingCart::getDishId,dishId);
        }else{
            //是套餐，并判断是哪一个套餐
            qw.eq(ShoppingCart::getSetmealId , setmealId);
        }
        //② 判断当前购物车内是否有目前即将要添加的菜品或套餐
        //SQL:select * from shopping_cart where user_id = ?
        //                      and dish_id/setmeal_id = ?
        ShoppingCart one = shoppingCartService.getOne(qw);
        if(one.getNumber() > 1){
            //大于一，在原来基础上数量减一
            one.setNumber(one.getNumber()-1);
            shoppingCartService.updateById(one);
        }else{
            //直接移除
            shoppingCartService.remove(qw);

        }
        return R.success(one);
    }
    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R clean(){

        //获取当前用户id
        Long userid = UserHolder.get();

        //根据当前登录用户id删除购物车数据
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userid);
        shoppingCartService.remove(lqw);

        return R.success("清空购物车成功");
    }
}
